const service = require('../service/user.service')
const errorType = require('../constants/errot-type')
const md5password = require('../utils/password-handle')
const verifyUser = async (ctx, next) => {
    console.log( ctx.request)
    const { username, password } = ctx.request.body

    //  判断用户名和密码不能为空 
    if(!username || !password) {
        const error = new Error(errorType.NAME_OR_PASSWORD_IS_REQUIRED)
        return ctx.app.emit('error', error, ctx)
    }

    // 判断用户是否存在
    const result = await service.getUserByName(username)
    if(result.length) {
        const error = new Error(errorType.USER_ALREADY_EXISTS)
        return ctx.app.emit('error', error, ctx)
    } 
    await next()
}

const handlePassword = async (ctx, next) => {
    const { password } = ctx.request.body
    ctx.request.body.password = md5password(password)
    await next()
}

module.exports = {
    verifyUser,
    handlePassword
}
